<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import {
  ElRow,
  ElCol,
  ElCard,
  ElSkeleton,
  ElDatePicker,
  ElButton,
  ElSelect,
  ElOption,
  ElAlert
} from 'element-plus'
import { Echart } from '@/components/Echart'
import { EChartsOption } from 'echarts'
import { useI18n } from '@/hooks/web/useI18n'
import {
  getAbnormalOrderStats,
  getOrderStats,
  getAbnormalTypeStats
} from '@/api/electricityAbnormal'

const { t } = useI18n()

// 页面状态
const loading = ref(true)
const filterForm = reactive({
  startDate: '',
  endDate: '',
  managementUnit: '',
  abnormalType: ''
})

// 统计数据
const statisticsData = reactive({
  totalOrders: 0,
  pendingOrders: 0,
  processingOrders: 0,
  completedOrders: 0,
  abnormalTypes: [] as any[]
})

// 饼图配置 - 异常类型分布
const pieOptions = ref<EChartsOption>({
  title: {
    text: '异常类型分布',
    left: 'center'
  },
  tooltip: {
    trigger: 'item',
    formatter: '{a} <br/>{b}: {c} ({d}%)'
  },
  legend: {
    orient: 'vertical',
    left: 10,
    data: []
  },
  series: [
    {
      name: '异常类型',
      type: 'pie',
      radius: ['50%', '70%'],
      avoidLabelOverlap: false,
      label: {
        show: false,
        position: 'center'
      },
      emphasis: {
        label: {
          show: true,
          fontSize: '14',
          fontWeight: 'bold'
        }
      },
      labelLine: {
        show: false
      },
      data: []
    }
  ]
})

// 柱状图配置 - 异常工单排名
const barOptions = ref<EChartsOption>({
  title: {
    text: '异常工单排名 (按管理单位)',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'shadow'
    }
  },
  xAxis: {
    type: 'category',
    data: [],
    axisLabel: {
      interval: 0,
      rotate: 30
    }
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '工单数量',
      type: 'bar',
      data: []
    }
  ]
})

// 线图配置 - 工单趋势
const lineOptions = ref<EChartsOption>({
  title: {
    text: '工单数量趋势',
    left: 'center'
  },
  tooltip: {
    trigger: 'axis'
  },
  xAxis: {
    type: 'category',
    data: []
  },
  yAxis: {
    type: 'value'
  },
  series: [
    {
      name: '工单数量',
      type: 'line',
      data: [],
      smooth: true
    }
  ]
})

// 获取异常工单统计数据
const getAbnormalOrderStatsData = async () => {
  try {
    const res = await getAbnormalOrderStats({
      startDate: filterForm.startDate,
      endDate: filterForm.endDate,
      managementUnit: filterForm.managementUnit,
      abnormalType: filterForm.abnormalType
    })

    if (res && res.data && res.data.code === 200) {
      const data = res.data.data

      // 更新统计数据
      statisticsData.totalOrders = data.totalOrders || 0
      statisticsData.pendingOrders = data.pendingOrders || 0
      statisticsData.processingOrders = data.processingOrders || 0
      statisticsData.completedOrders = data.completedOrders || 0

      // 更新异常工单排名柱状图
      if (data.rankByUnit && Array.isArray(data.rankByUnit)) {
        barOptions.value.xAxis.data = data.rankByUnit.map((item) => item.name)
        barOptions.value.series[0].data = data.rankByUnit.map((item) => item.value)
      }
    }
  } catch (error) {
    console.error('获取异常工单统计失败:', error)
  }
}

// 获取工单统计数据
const getOrderStatsData = async () => {
  try {
    const res = await getOrderStats({
      startDate: filterForm.startDate,
      endDate: filterForm.endDate,
      managementUnit: filterForm.managementUnit,
      abnormalType: filterForm.abnormalType
    })

    if (res && res.data && res.data.code === 200) {
      const data = res.data.data

      // 更新工单趋势线图
      if (data.trendByMonth && Array.isArray(data.trendByMonth)) {
        lineOptions.value.xAxis.data = data.trendByMonth.map((item) => item.month)
        lineOptions.value.series[0].data = data.trendByMonth.map((item) => item.count)
      }
    }
  } catch (error) {
    console.error('获取工单统计失败:', error)
  }
}

// 获取异常类型统计数据
const getAbnormalTypeStatsData = async () => {
  try {
    const res = await getAbnormalTypeStats({
      startDate: filterForm.startDate,
      endDate: filterForm.endDate,
      managementUnit: filterForm.managementUnit
    })

    if (res && res.data && res.data.code === 200) {
      const data = res.data.data

      // 更新异常类型统计数据
      if (data.typeStats && Array.isArray(data.typeStats)) {
        statisticsData.abnormalTypes = data.typeStats

        // 更新饼图数据
        pieOptions.value.legend.data = data.typeStats.map((item) => item.name)
        pieOptions.value.series[0].data = data.typeStats.map((item) => ({
          name: item.name,
          value: item.count
        }))
      }
    }
  } catch (error) {
    console.error('获取异常类型统计失败:', error)
  }
}

// 获取所有统计数据
const getAllStats = async () => {
  loading.value = true
  try {
    await Promise.all([
      getAbnormalOrderStatsData(),
      getOrderStatsData(),
      getAbnormalTypeStatsData()
    ])
  } catch (error) {
    console.error('获取统计数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 筛选条件变更时重新获取数据
const handleFilterChange = () => {
  getAllStats()
}

// 重置筛选条件
const resetFilter = () => {
  filterForm.startDate = ''
  filterForm.endDate = ''
  filterForm.managementUnit = ''
  filterForm.abnormalType = ''
  getAllStats()
}

// 组件挂载时获取数据
onMounted(() => {
  // 设置默认日期范围为近3个月
  const now = new Date()
  const threeMonthsAgo = new Date()
  threeMonthsAgo.setMonth(now.getMonth() - 3)

  filterForm.endDate = now.toISOString().split('T')[0]
  filterForm.startDate = threeMonthsAgo.toISOString().split('T')[0]

  // 获取所有统计数据
  getAllStats()
})
</script>

<template>
  <div class="electricity-abnormal-analysis">
    <!-- 筛选条件 -->
    <ElCard shadow="hover" class="mb-20px">
      <div class="filter-container">
        <ElRow :gutter="20">
          <ElCol :span="6">
            <div class="filter-item">
              <span class="filter-label">日期范围:</span>
              <ElDatePicker
                v-model="filterForm.startDate"
                type="date"
                placeholder="开始日期"
                style="width: 140px"
                value-format="YYYY-MM-DD"
                class="mr-10px"
              />
              <span class="mx-5px">至</span>
              <ElDatePicker
                v-model="filterForm.endDate"
                type="date"
                placeholder="结束日期"
                style="width: 140px"
                value-format="YYYY-MM-DD"
              />
            </div>
          </ElCol>
          <ElCol :span="4">
            <div class="filter-item">
              <span class="filter-label">管理单位:</span>
              <ElSelect
                v-model="filterForm.managementUnit"
                placeholder="请选择"
                style="width: 140px"
              >
                <ElOption label="全部" value="" />
                <ElOption label="广州供电局" value="广州供电局" />
                <ElOption label="深圳供电局" value="深圳供电局" />
                <ElOption label="佛山供电局" value="佛山供电局" />
                <ElOption label="东莞供电局" value="东莞供电局" />
              </ElSelect>
            </div>
          </ElCol>
          <ElCol :span="4">
            <div class="filter-item">
              <span class="filter-label">异常类型:</span>
              <ElSelect v-model="filterForm.abnormalType" placeholder="请选择" style="width: 140px">
                <ElOption label="全部" value="" />
                <ElOption label="电量异常" value="01" />
                <ElOption label="电费异常" value="02" />
                <ElOption label="计量异常" value="03" />
              </ElSelect>
            </div>
          </ElCol>
          <ElCol :span="10" class="text-right">
            <ElButton type="primary" @click="handleFilterChange">查询</ElButton>
            <ElButton @click="resetFilter" class="ml-10px">重置</ElButton>
          </ElCol>
        </ElRow>
      </div>
    </ElCard>

    <!-- 统计卡片 -->
    <ElRow :gutter="20" class="mb-20px">
      <ElCol :span="6">
        <ElCard shadow="hover" class="stat-card total">
          <div class="stat-title">工单总数</div>
          <div class="stat-value">{{ statisticsData.totalOrders }}</div>
        </ElCard>
      </ElCol>
      <ElCol :span="6">
        <ElCard shadow="hover" class="stat-card pending">
          <div class="stat-title">待处理工单</div>
          <div class="stat-value">{{ statisticsData.pendingOrders }}</div>
        </ElCard>
      </ElCol>
      <ElCol :span="6">
        <ElCard shadow="hover" class="stat-card processing">
          <div class="stat-title">处理中工单</div>
          <div class="stat-value">{{ statisticsData.processingOrders }}</div>
        </ElCard>
      </ElCol>
      <ElCol :span="6">
        <ElCard shadow="hover" class="stat-card completed">
          <div class="stat-title">已完成工单</div>
          <div class="stat-value">{{ statisticsData.completedOrders }}</div>
        </ElCard>
      </ElCol>
    </ElRow>

    <!-- 图表 -->
    <ElRow :gutter="20">
      <ElCol :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <ElCard shadow="hover" class="mb-20px chart-card">
          <ElSkeleton :loading="loading" animated>
            <Echart :options="pieOptions" :height="350" />
          </ElSkeleton>
        </ElCard>
      </ElCol>
      <ElCol :xl="12" :lg="12" :md="24" :sm="24" :xs="24">
        <ElCard shadow="hover" class="mb-20px chart-card">
          <ElSkeleton :loading="loading" animated>
            <Echart :options="barOptions" :height="350" />
          </ElSkeleton>
        </ElCard>
      </ElCol>
      <ElCol :span="24">
        <ElCard shadow="hover" class="mb-20px chart-card">
          <ElSkeleton :loading="loading" animated :rows="4">
            <Echart :options="lineOptions" :height="350" />
          </ElSkeleton>
        </ElCard>
      </ElCol>
    </ElRow>

    <!-- 异常类型详情 -->
    <ElCard shadow="hover" class="mb-20px" v-if="statisticsData.abnormalTypes.length > 0">
      <template #header>
        <div class="card-header">
          <span>异常类型详情</span>
        </div>
      </template>
      <div class="abnormal-type-list">
        <div
          v-for="(type, index) in statisticsData.abnormalTypes"
          :key="index"
          class="abnormal-type-item"
        >
          <div class="type-name">{{ type.name }}</div>
          <div class="type-count">{{ type.count }}个工单</div>
          <div class="type-percentage"
            >{{ ((type.count / statisticsData.totalOrders) * 100).toFixed(2) }}%</div
          >
        </div>
      </div>
    </ElCard>

    <ElAlert
      v-if="!loading && statisticsData.totalOrders === 0"
      title="暂无数据"
      type="info"
      description="在选定的时间范围和筛选条件下没有找到电费异常数据。请尝试调整筛选条件或日期范围。"
      show-icon
      :closable="false"
      center
    />
  </div>
</template>

<style lang="scss" scoped>
.electricity-abnormal-analysis {
  padding: 20px 0;

  .filter-container {
    .filter-item {
      display: flex;
      align-items: center;
      margin-bottom: 16px;

      .filter-label {
        min-width: 80px;
        margin-right: 8px;
      }
    }
  }

  .stat-card {
    text-align: center;
    height: 120px;
    display: flex;
    flex-direction: column;
    justify-content: center;

    .stat-title {
      font-size: 16px;
      color: #606266;
      margin-bottom: 8px;
    }

    .stat-value {
      font-size: 28px;
      font-weight: bold;
    }

    &.total {
      .stat-value {
        color: #409eff;
      }
    }

    &.pending {
      .stat-value {
        color: #e6a23c;
      }
    }

    &.processing {
      .stat-value {
        color: #67c23a;
      }
    }

    &.completed {
      .stat-value {
        color: #909399;
      }
    }
  }

  .chart-card {
    height: 100%;
  }

  .abnormal-type-list {
    display: flex;
    flex-wrap: wrap;
    gap: 20px;

    .abnormal-type-item {
      background-color: #f8f9fa;
      border-radius: 8px;
      padding: 16px;
      width: calc(25% - 15px);
      text-align: center;

      .type-name {
        font-size: 16px;
        font-weight: bold;
        margin-bottom: 8px;
      }

      .type-count {
        font-size: 20px;
        color: #409eff;
        margin-bottom: 4px;
      }

      .type-percentage {
        font-size: 14px;
        color: #909399;
      }
    }
  }

  .card-header {
    font-size: 16px;
    font-weight: bold;
  }

  .text-right {
    text-align: right;
  }

  .mr-10px {
    margin-right: 10px;
  }

  .ml-10px {
    margin-left: 10px;
  }

  .mx-5px {
    margin: 0 5px;
  }

  .mb-20px {
    margin-bottom: 20px;
  }
}

@media (max-width: 1200px) {
  .electricity-abnormal-analysis {
    .abnormal-type-list {
      .abnormal-type-item {
        width: calc(33.33% - 14px);
      }
    }
  }
}

@media (max-width: 768px) {
  .electricity-abnormal-analysis {
    .abnormal-type-list {
      .abnormal-type-item {
        width: calc(50% - 10px);
      }
    }
  }
}
</style>
